package com.zhugang.week13.stack;

import java.util.Stack;

/**
 * @program algorithms
 * @description: MinStack
 * @author: chanzhugang
 * @create: 2022/11/03 15:57
 */
public class MinStack {

    /**
     * 155 最小栈
     * https://leetcode.cn/problems/min-stack/
     * 原来的栈操作不变，维护一个最小栈，栈顶元素是最小值
     */

    Stack<Integer> stack = new Stack<>();
    Stack<Integer> minStack = new Stack<>();

    public MinStack() {

    }

    /**
     * 维护一个最小栈，不好想，画图理解
     *
     * @param val
     */
    public void push(int val) {
        if (stack.isEmpty()) {
            minStack.push(val);
        } else {
            // 最小栈栈顶元素和val 比较
            Integer curMin = minStack.peek();
            curMin = Math.min(curMin, val);
            minStack.push(curMin);
        }
        stack.push(val);
    }

    public void pop() {
        // 实时更新最小栈
        stack.pop();
        minStack.pop();
    }

    public int top() {
        if (stack.isEmpty()) {
            return -1;
        }
        return stack.peek();
    }

    public int getMin() {
        if (minStack.isEmpty()) {
            return -1;
        }
        return minStack.peek();
    }
}